package com.voice.core.connection.frame;

import java.util.Arrays;

public abstract class AbstractFrame extends Frame {

    private boolean isFlagSet(byte mask) {
        return (this.flag & mask) != 0;
    }

    private void setFlag(boolean on, byte mask) {
        if (on) flag = (byte)(flag | mask);
        else flag = (byte) (flag & ~mask);
    }

    public boolean endOfStream() {
        return isFlagSet((byte) 1);
    }

    public boolean ack() {
        return isFlagSet((byte) 2);
    }

    public boolean endHeaders() {
        return isFlagSet((byte) 4);
    }

    public boolean padded() {
        return isFlagSet((byte) 8);
    }

    public boolean priority() {
        return isFlagSet((byte) 32);
    }

    public void endOfStream(boolean endOfStream) {
        setFlag(endOfStream, (byte) 1);
    }

    public void ack(boolean ack) {
        setFlag(ack, (byte) 2);
    }

    public void endHeaders(boolean endHeaders) {
        setFlag(endHeaders, (byte) 4);
    }

    public void padded(boolean padded) {
        setFlag(padded, (byte) 8);
    }

    public void priority(boolean priority) {
        setFlag(priority, (byte) 32);
    }

    @Override
    public byte[] getData() {
        return Arrays.copyOfRange(payload, headerLength,payload.length);
    }

    public byte getPaddingLength(){
        return payload[headerLength];
    }

    public byte getWeight(){
        if(!priority()) return 0;
        return payload[headerLength+5];
    }
}
